package com.lemon.core.redis.config;

import java.time.temporal.ChronoUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.convert.DurationStyle;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.util.StringUtils;

/**
 * 自定义Redis缓存管理器
 *
 * @author pan
 * @link https://blog.csdn.net/f641385712/article/details/95234347
 * @since 2019-08-09
 */
@Slf4j
public class RedisAutoCacheManager extends RedisCacheManager {

    public RedisAutoCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 创建缓存，从 cache name 中解析 ttl，例如： user:test#300ms，不带单位默认为 s 秒
     *
     * @param name cacheName cache#3600
     */
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] array = StringUtils.delimitedListToStringArray(name, "#");
        // 解析TTL
        if (array.length > 1) {
            name = array[0];
            // 注意此处单位用的是秒，而非毫秒
            cacheConfig = cacheConfig.entryTtl(DurationStyle.detectAndParse(array[1], ChronoUnit.SECONDS));
        }
        return super.createRedisCache(name, cacheConfig);
    }

}
